package com.fbee.smartcommunities.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fbee.smartcommunities.entity.Cart;
import com.fbee.smartcommunities.entity.Goods;
import com.fbee.smartcommunities.entity.Shop;
import com.fbee.smartcommunities.entity.User;
import com.fbee.smartcommunities.mapper.CartMapper;
import com.fbee.smartcommunities.mapper.GoodsMapper;
import com.fbee.smartcommunities.mapper.ShopMapper;
import com.fbee.smartcommunities.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fbee.smartcommunities.service.UploadFileService;
import com.fbee.smartcommunities.utils.StringUtil;
import io.minio.errors.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author 汪佳泉
 * @since 2024-08-16
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private UploadFileService uploadFileService;

    @Override
    public Page<Goods> getTargetList(Integer pageNo, Integer pageSize, String keyword, Integer categoryId) {
        // 创建分页对象
        Page<Goods> page = new Page<>(pageNo,pageSize);
        // 创建条件构造器
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        // 添加查询条件
        if(keyword != null){
            queryWrapper.like("name",keyword);
        }
        if(categoryId != null){
            queryWrapper.eq("category_id",categoryId);
        }
        return goodsMapper.selectPage(page,queryWrapper);
    }

    @Override
    public Page<Goods> getBusinessPage(Integer pageNo, Integer pageSize, Integer stateUser,Long openId, String sortType, String sortDetail,Integer typeId,String goodsName) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if(goodsName != null){
            queryWrapper.like("name",goodsName);
        }
        if(typeId != null){
            queryWrapper.eq("category_id",typeId);
        }
        if(sortType != null && sortType != null){
            if( "price".equals(sortType) ){
                if("price_up".equals(sortDetail)){
                    queryWrapper.orderByAsc("price");
                } else {
                    queryWrapper.orderByDesc("price");
                }
            } else if( "sell".equals(sortType) ){
                if("sell_up".equals(sortDetail)){
                    queryWrapper.orderByAsc("sales");
                } else {
                    queryWrapper.orderByDesc("sales");
                }
            } else if( "stock".equals(sortType) ){
                if("stock_up".equals(sortDetail)){
                    queryWrapper.orderByAsc("store");
                } else {
                    queryWrapper.orderByDesc("store");
                }
            } else if( "time".equals(sortType) ){
                if("time_up".equals(sortDetail)){
                    queryWrapper.orderByAsc("create_time");
                } else {
                    queryWrapper.orderByDesc("create_time");
                }
            }
        }
        Shop shop = shopMapper.selectOne(new QueryWrapper<Shop>().eq("user_id",openId));
        queryWrapper.eq("shop_id",shop.getId());
        if(stateUser == null){
            queryWrapper.ne("state_user",-1);
        } else {
            queryWrapper.eq("state_user",stateUser);
        }
        return goodsMapper.selectPage(new Page<Goods>(pageNo,pageSize),queryWrapper);
    }

    @Override
    public Page<Goods> getPage(Integer pageNo, Integer pageSize) {
        System.out.println(pageNo + "   " + pageSize);
        Page<Goods> goodsPage = new Page<>(pageNo, pageSize);
        return goodsMapper.getPage(goodsPage);
    }

    @Override
    public Boolean fixState(Long id, Boolean state,String key) {
        UpdateWrapper<Goods> goodsUpdateWrapper = new UpdateWrapper<>();
        if("sta".equals(key)){
            goodsUpdateWrapper.set("state",!state).eq("id",id);
        } else {
            goodsUpdateWrapper.set("recommend",!state).eq("id",id);
        }
        return this.update(goodsUpdateWrapper);
    }

    @Override
    public Goods getById(Long id) {
        return goodsMapper.getById(id);
    }

    @Override
    public Boolean increaseBrowse(Long id) {
        Goods goods = goodsMapper.selectById(id);
        this.update(new UpdateWrapper<Goods>().eq("id",id).set("browse",goods.getBrowse() + 1));
        return true;
    }

    @Override
    public Boolean updateStateUserForBatch(Integer[] ids, Long stateUser) {
        for (Integer id : ids) {
            update(new UpdateWrapper<Goods>().eq("id", id).set("state_user", stateUser));
        }
        return true;
    }

    @Override
    public Boolean updateGoods(Long id, String name, String description, Double discount, Double price, Integer store, MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id)
                .set("name",name)
                .set("description",description)
                .set("discount",discount)
                .set("price",price)
                .set("store",store);
        if(file != null) {
            String upload = uploadFileService.upload("goods", file);
            updateWrapper.set("imgs",upload);
        }
        return this.update(null,updateWrapper);
    }

    @Override
    @Transactional
    public Boolean addGoods(Long categoryId,
                            String name,
                            Integer count,
                            String description,
                            Double price,
                            MultipartFile file,
                            Long openId) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String path = null;
        if(file != null){
            path = uploadFileService.upload("goods", file);
        }
        // 由openId来获取对应店铺的id
        Shop shop = shopMapper.selectOne(new QueryWrapper<Shop>().eq("user_id", openId));
        Goods goods = new Goods(name, description, StringUtil.generateUniqueId(), new BigDecimal(price),new BigDecimal(0),count,0,0,0, categoryId, path, LocalDateTime.now(),1,shop.getId().longValue(),0,0);
        return this.save(goods);
    }

    @Override
    public List<Integer> getGoodsStore(Long[] ids) {
        ArrayList<Integer> list = new ArrayList<>();
        if(ids != null){
            for (Long id : ids) {
                list.add(goodsMapper.getGoodsStore(id));
            }
        }
        return list;
    }


}
